/*
  学习目标：组件通信-子传父, 儿子划掉爸爸赚的钱

*/

import React from 'react';
export default class App extends React.Component {
  state = {
    money: 1000,
  };

  handleMakeMoney = () => {
    this.setState({
      money: 1000 + this.state.money,
    });
  };

  render() {
    const { money } = this.state;
    return (
      <div>
        <h1>{money}</h1>
        <button onClick={this.handleMakeMoney}>爸爸开始赚钱了</button>
        <Child
          // 2. 💥通过props, 传回调函数给子组件
          handleCost={this.handleCost}
          money={money}
        ></Child>
      </div>
    );
  }

  // 1. 父组件内定义一个花钱的函数
  handleCost = (num) => {
    console.log('num  ----->  ', num);
    // 4, 完成计算
    this.setState({
      money: this.state.money - num,
    });
  };
}

class Child extends React.Component {
  render() {
    const { money, handleCost } = this.props;
    console.log('handleCost  ----->  ', handleCost);
    return (
      <div>
        <h1>爸爸给我钱了： {money}</h1>

        <button
          onClick={() => {
            // 3. 💥子组件调用回调函数
            handleCost(8000);
          }}
        >
          我要花钱
        </button>
      </div>
    );
  }
}
